import Util from '../utils/util'

export default {
  data () {
    return {
      starY: 0
    }
  },

  mounted () {
    let _this = this
    this.$nextTick(function () {
      document.body.addEventListener('touchstart', _this.touchstartFunction, { passive: false })
      // 需要滑动的dom元素
      if (Util.isIos()) {
        this.iosTrouchFn('.forbidScrollA')
        this.iosTrouchFn('.forbidScrollB')
      }
    })
  },

  beforeDestroy () {
    // 移除事件监听
    let _this = this
    document.body.removeEventListener('touchstart', _this.touchstartFunction, { passive: false })
    document.body.removeEventListener('touchmove', _this.touchmoveFunction, { passive: false })
  },

  methods: {
    touchmoveFunction (e) {
      let el = document.querySelector('.forbidScroll')
      // 需要滑动的dom元素
      if (!e.isSCROLL) {
        e.preventDefault() // 阻止默认事件(上下滑动)
        // console.log('阻止了')
      } else {
        // 需要滑动的区域
        let moveY = e.touches[0].pageY
        let top = el.scrollTop
        let ch = el.clientHeight// 对象最顶端和窗口最顶端之间的距离
        let scrollH = el.scrollHeight // 含滚动内容的元素大小
        if ((top === 0 && moveY > this.startY) || (top + ch === scrollH && moveY < this.startY)) {
          e.preventDefault()
          // console.log('阻止了')
        } else {
          // console.log('开启了')
        }
      }
    },

    touchstartFunction (e) {
      this.starY = e.touches[0].pageY
    },

    iosTrouchFn (tag) {
      let el = document.querySelector(tag)
      // el需要滑动的元素
      el.addEventListener('touchmove', function (e) {
        e.isSCROLL = true
      })
      document.body.addEventListener('touchmove', this.touchmoveFunction, { passive: false })
      // passive防止阻止默认事件不生效
    }
  }
}
